package com.youdao.note.task;

import android.os.Handler;
import android.os.Message;
import com.youdao.note.YNoteApplication;
import com.youdao.note.data.Note;
import com.youdao.note.data.NoteBook;
import com.youdao.note.data.NoteMeta;
import com.youdao.note.data.ProgressData;
import com.youdao.note.data.RemoteErrorData;
import com.youdao.note.data.UserMeta;
import com.youdao.note.data.resource.BaseResourceMeta;
import com.youdao.note.datasource.DataSource;
import com.youdao.note.exceptions.ResourceMissingException;
import com.youdao.note.exceptions.UnloginException;
import com.youdao.note.utils.Consts.DATA_TYPE;
import com.youdao.note.utils.L;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.http.entity.mime.MultipartUploadListener;

class Syncer extends AsyncTaskWithExecuteResult<Void, ProgressData, Boolean>
  implements Consts.DATA_TYPE
{
  private static final long FAKE_UPDATE_INTERVAL = 1000L;
  private static final int FAKE_UPDATE_V = 50;
  private static int FIXED_REQUEST_SIZE = 0;
  private static final int MESSAGE_FAKE_UPDATE = 1;
  private boolean bRunInBackGround;
  private DataSource mDataSource = null;
  private Handler mHandler = new Handler()
  {
    public void handleMessage(Message paramMessage)
    {
      if ((paramMessage.what != 1) || (paramMessage.arg1 <= 0))
        return;
      Message localMessage = Syncer.this.mHandler.obtainMessage(1);
      localMessage.arg1 = (-50 + paramMessage.arg1);
      Syncer.this.mHandler.sendMessageDelayed(localMessage, 1000L);
      Syncer.this.publishProgress(50L);
    }
  };
  private long mStartTime = System.currentTimeMillis();
  private SyncFinishListener mSyncFinishListener = null;
  private TaskManager mTaskManager = null;
  private YNoteApplication mYNote = null;
  private ProgressData progress = new ProgressData(0);
  private int totalSize = 3 * FIXED_REQUEST_SIZE;
  private int uploadedSize = 0;

  public Syncer(TaskManager paramTaskManager, DataSource paramDataSource, boolean paramBoolean)
  {
    this.mTaskManager = paramTaskManager;
    this.mDataSource = paramDataSource;
    this.bRunInBackGround = paramBoolean;
    this.mYNote = YNoteApplication.getInstance();
  }

  private void calculatePushSize(List<NoteMeta> paramList, List<List<BaseResourceMeta>> paramList1)
  {
    Iterator localIterator1 = paramList.iterator();
    if (!localIterator1.hasNext())
      return;
    NoteMeta localNoteMeta = (NoteMeta)localIterator1.next();
    if (localNoteMeta.isDeleted())
      this.totalSize += FIXED_REQUEST_SIZE;
    while (true)
    {
      List localList = this.mDataSource.getDirtyResourcesOf(localNoteMeta);
      paramList1.add(localList);
      Iterator localIterator2 = localList.iterator();
      while (true)
      {
        if (localIterator2.hasNext());
        BaseResourceMeta localBaseResourceMeta = (BaseResourceMeta)localIterator2.next();
        this.totalSize = (int)(this.totalSize + localBaseResourceMeta.getLength());
      }
      this.totalSize = (int)(this.totalSize + localNoteMeta.getLength());
      if (!localNoteMeta.isMoved())
        continue;
      this.totalSize += FIXED_REQUEST_SIZE;
    }
  }

  private Boolean innerSync()
    throws Exception
  {
    L.d(this, "Syncer is running");
    Message localMessage = this.mHandler.obtainMessage(1);
    localMessage.arg1 = (int)(0.96D * this.totalSize);
    this.mHandler.sendMessage(localMessage);
    this.mTaskManager.pullNotesIfNecessary(false);
    Iterator localIterator1 = this.mDataSource.getDirtyNoteBookMetas().iterator();
    while (localIterator1.hasNext())
    {
      NoteBook localNoteBook = (NoteBook)localIterator1.next();
      this.mTaskManager.updateMeta(localNoteBook, false);
    }
    List localList = this.mDataSource.getDirtyAndMovedNoteMetas();
    ArrayList localArrayList = new ArrayList(localList.size());
    calculatePushSize(localList, localArrayList);
    publishProgress(FIXED_REQUEST_SIZE);
    L.d(this, "Total size is " + this.totalSize);
    L.d(this, "Total dirty notes are " + localList.size());
    boolean bool1 = true;
    Iterator localIterator2 = localList.iterator();
    while (localIterator2.hasNext())
    {
      NoteMeta localNoteMeta2 = (NoteMeta)localIterator2.next();
      if (!localNoteMeta2.isDeleted())
        continue;
      L.d(this, "Try to delete note " + localNoteMeta2.getTitle());
      this.mTaskManager.delNote(localNoteMeta2.getEntryPath(), false);
      publishProgress(FIXED_REQUEST_SIZE);
    }
    int i = 0;
    Iterator localIterator3 = localList.iterator();
    while (localIterator3.hasNext())
    {
      NoteMeta localNoteMeta1 = (NoteMeta)localIterator3.next();
      if (localNoteMeta1.isMoved())
      {
        L.d(this, "Try to move note " + localNoteMeta1.getTitle());
        bool1 &= this.mTaskManager.moveNote(localNoteMeta1, false);
        publishProgress(FIXED_REQUEST_SIZE);
      }
      if ((!localNoteMeta1.isDeleted()) && (localNoteMeta1.isDirty()))
      {
        L.d(this, "Try to push note " + localNoteMeta1.getTitle());
        bool1 &= pushNote(localNoteMeta1, (List)localArrayList.get(i));
      }
      ++i;
    }
    this.mTaskManager.pullNotesIfNecessary(false);
    publishProgress(FIXED_REQUEST_SIZE);
    if (!this.mTaskManager.pullNotesIfNecessary(false));
    for (boolean bool2 = true; ; bool2 = false)
    {
      boolean bool3 = bool1 & bool2;
      publishProgress(FIXED_REQUEST_SIZE);
      L.d(this, "synce result is " + bool3);
      if (bool3)
        updateLastSyncTime();
      return Boolean.valueOf(bool3);
    }
  }

  private void updateLastSyncTime()
  {
    UserMeta localUserMeta = this.mDataSource.getUserMeta();
    if (localUserMeta == null)
      this.mTaskManager.pullUserMeta(false);
    if (localUserMeta == null)
      return;
    localUserMeta.setLastSynceTime(System.currentTimeMillis());
    this.mDataSource.insertOrUpdateUserMeta(YNoteApplication.getInstance().getUserName(), localUserMeta);
  }

  public int getProgress()
  {
    int i = 100 * this.uploadedSize / this.totalSize;
    if (i >= 100)
      this.mHandler.removeMessages(1);
    if (i < 100)
      return i;
    return 100;
  }

  public long getStartTime()
  {
    return this.mStartTime;
  }

  protected Boolean innerRun(Void[] paramArrayOfVoid)
    throws Exception
  {
    if (!this.mYNote.isLogin())
    {
      L.d(this, "User not login return false");
      throw new UnloginException();
    }
    if ((this.mYNote.syncOnlyUnderWifi()) && (!this.mYNote.isWifiAvailable()) && (this.bRunInBackGround))
    {
      L.d(this, "Not under wifi, sync cancled.");
      return Boolean.valueOf(false);
    }
    return innerSync();
  }

  public boolean isRunInBackGround()
  {
    return this.bRunInBackGround;
  }

  protected void onFailed(Exception paramException)
  {
    if (this.bRunInBackGround)
      return;
    L.e(this, "Failed to sync", paramException);
    this.mTaskManager.updateResult(6, new RemoteErrorData(paramException), false);
  }

  protected void onPostExecute(Boolean paramBoolean)
  {
    if (this.mSyncFinishListener != null)
      this.mSyncFinishListener.onSyncFinished();
    L.d(this, "sync result is " + paramBoolean);
    if ((paramBoolean != null) && (!paramBoolean.booleanValue()))
      setExecuteResult(false);
    super.onPostExecute(paramBoolean);
  }

  protected void onProgressUpdate(ProgressData[] paramArrayOfProgressData)
  {
    if (this.bRunInBackGround)
      return;
    this.mTaskManager.updateResult(7, paramArrayOfProgressData[0], true);
  }

  protected void onSucceed(Boolean paramBoolean)
  {
    if (this.bRunInBackGround)
      return;
    this.mTaskManager.updateResult(6, null, paramBoolean.booleanValue());
  }

  public void publishProgress(long paramLong)
  {
    this.uploadedSize = (int)(paramLong + this.uploadedSize);
    this.progress.setProgress(getProgress());
    ProgressData[] arrayOfProgressData = new ProgressData[1];
    arrayOfProgressData[0] = this.progress;
    super.publishProgress(arrayOfProgressData);
  }

  public boolean pushNote(NoteMeta paramNoteMeta, List<BaseResourceMeta> paramList)
    throws Exception
  {
    HashMap localHashMap = new HashMap(4);
    Iterator localIterator = paramList.iterator();
    label17: BaseResourceMeta localBaseResourceMeta;
    if (localIterator.hasNext())
      localBaseResourceMeta = (BaseResourceMeta)localIterator.next();
    Note localNote;
    do
    {
      try
      {
        2 local2 = new MultipartUploadListener()
        {
          public void onUploaded(long paramLong)
          {
            Syncer.this.publishProgress(paramLong);
          }
        };
        boolean bool = this.mTaskManager.pushResource(localBaseResourceMeta, local2);
        if (!bool)
          return false;
      }
      catch (FileNotFoundException localFileNotFoundException)
      {
        throw new ResourceMissingException(paramNoteMeta.getTitle(), localFileNotFoundException);
      }
      localHashMap.put(localBaseResourceMeta.getResourceId(), localBaseResourceMeta);
      break label17:
      L.d(this, paramNoteMeta.getTitle() + " " + paramList.size());
      localNote = this.mDataSource.getNote(paramNoteMeta);
    }
    while (!this.mTaskManager.pushNote(localNote, localHashMap));
    publishProgress(paramNoteMeta.getLength());
    return true;
  }

  public void setOnSyncFinishListener(SyncFinishListener paramSyncFinishListener)
  {
    this.mSyncFinishListener = paramSyncFinishListener;
  }

  protected Boolean syncExecute()
  {
    Boolean localBoolean = (Boolean)doInBackground(new Void[0]);
    onPostExecute(localBoolean);
    return localBoolean;
  }

  public static abstract interface SyncFinishListener
  {
    public abstract void onSyncFinished();
  }
}

/* Location:           D:\soft\dex2jar-0.0.9.15\classes-dex2jar.jar
 * Qualified Name:     com.youdao.note.task.Syncer
 * JD-Core Version:    0.5.4
 */